import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:news_flutter/models/news_model.dart';
import 'package:news_flutter/pages/index//news_types_manage_page.dart';
import 'package:news_flutter/pages/index/search_news_list_page.dart';
import 'package:news_flutter/utils/http_request_util.dart';
import 'package:news_flutter/widgets/custom/my_appbar_widget.dart';
import 'package:news_flutter/utils/precompile.dart';
import 'package:news_flutter/utils/my_navigator.dart';
import 'package:news_flutter/widgets/custom/refresh_tableview_widget.dart';
import 'package:news_flutter/widgets/news/news_items_widget.dart';

//数据容器，存放分类和分类下的数据
class _DataContainer {
  //
  String name;
  int page =1;
  List list = [];

  //是否获从接口获取过数据
  bool hasLoaded = false;

  _DataContainer(this.name);
  void acceptData(List newList ,{bool isRefresh =false}){
    hasLoaded = true;
    if (isRefresh ==true){
      list = newList;
    }
    else{
      list = list + newList;
    }
  }
}

class NewsListPage extends StatefulWidget {
  @override
  _NewsListPageState createState() => _NewsListPageState();
}

class _NewsListPageState extends State<NewsListPage>
    with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin {

  //类目
  List _types = [
    "关注",
    "头条",
    "抗疫",
    "视频",
    "娱乐",
    "体育",
    "新时代",
    "要闻",
    "财经",
    "科技",
    "本地"
  ];
  List<_DataContainer> _datas = [];
  TabController _tabController;
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < _types.length; i++) {
      String name = _types[i];
      _DataContainer container = _DataContainer(name);
      _datas.add(container);
    }
    _tabController = TabController(
      length: _datas.length,
      vsync: this,
    );
    _tabController.addListener(() {
      if (_tabController.index == _tabController.animation.value) {
        _loadData(isRefresh: true);
      }
    });
    _loadData(isRefresh: true);
  }

  @override
  void dispose() {
    _tabController.removeListener(() {});
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        //左边logo
        leading: Container(
          width: 64,
          height: 44,
          padding: EdgeInsets.only(left: 10),
          child: Image(
            image: AssetImage("assets/images/logo.png"),
          ),
        ),
        //搜索框
        title: _searchInputWidget(),
        actions: <Widget>[
          //热门新闻
          Container(
            width: 44,
            child: IconButton(
              icon: Icon(Icons.whatshot),
              padding: EdgeInsets.zero,
              onPressed: () {
                _goHotNewsPage();
              },
            ),
          ),
          //消息
          Container(
            width: 44,
            child: IconButton(
              icon: Icon(Icons.chat_bubble_outline),
              padding: EdgeInsets.zero,
              onPressed: () {
                _goMsgPage();
              },
            ),
          ),
        ],
      ),
      body: Column(
        children: <Widget>[
          _tabBar(),
          Expanded(
            child: _tabBarView(),
          ),
        ],
      ),
    );
  }

  //搜索框
  Widget _searchInputWidget() {
    return InkWell(
      onTap: () {
        //跳转到搜索
        _goSearchPage();
      },
      child: Container(
        height: 34,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(17)),
            color: Colors.white.withOpacity(0.4)),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              //放大镜
              Container(
                margin: EdgeInsets.only(right: 5),
                child: Icon(
                  Icons.search,
                  color: Colors.white,
                ),
              ),
              //热门关键词
              Text(
                "热门关键词",
                style: TextStyle(fontSize: 14, color: Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }

  //tabbar
  Widget _tabBar() {
    return Container(
      height: 44,
      child: Row(
        children: [
          Expanded(
            child: TabBar(
              //设置tab是否可水平滑动
              isScrollable: true,
              //控制器
              controller: _tabController,
              indicatorColor: Colors.black,
              indicatorSize: TabBarIndicatorSize.label,
              indicatorWeight: 2,
              labelPadding: EdgeInsets.zero,
              labelStyle: TextStyle(fontSize: 16),
              labelColor: Colors.black,
              unselectedLabelColor: MyColor.TEXT_GRAY,
              indicatorPadding: EdgeInsets.symmetric(horizontal: 15),
              tabs: _datas.map((item) {
                return Container(
                  margin: EdgeInsets.only(left: 10, right: 10),
                  child: Tab(text: item.name),
                );
              }).toList(),
            ),
          ),
          Container(
            width: 44,
            child: IconButton(
              icon: Icon(
                Icons.more_horiz,
                color: Colors.black,
              ),
              onPressed: () {
                _goNewsTypesManage();
              },
            ),
          ),
        ],
      ),
    );
  }

  //tabbarview
  Widget _tabBarView() {
    return TabBarView(
      controller: _tabController,
      children: _datas.map((item) {
        return _listView(item);
      }).toList(),
    );
  }

  //单个ListView
  Widget _listView(_DataContainer container) {
    return RefreshTableView(
      onRefresh: (){
        _loadData(isRefresh: true);
      },
      onLoadMore: (){
        _loadData();
      },
      itemBuilder: (BuildContext context, int index) {
        return NewsItemWidget(
          newsModel: container.list[index],
        );
      },
      itemCount: container.list.length,

    );
  }

  //跳转到搜索
  void _goSearchPage() {
    MyNavigator.push(context, SearchNewsListPage(),fullscreenDialog: true);
  }

  //跳转到热门
  void _goHotNewsPage() {}

  //跳转到消息
  void _goMsgPage() {}

  //跳转到新闻分类管理
  void _goNewsTypesManage() async {
    Widget page = NewsTypesManagePage();
    var result = await MyNavigator.push(context, page);
    print("pop result =$result");
  }

  //加载数据
  void _loadData({bool isRefresh=false}) {
    _DataContainer container = _datas[_tabController.index];
    if (isRefresh ==true){
      container.page =1;
    }
    else{
      container.page++;
    }
    print("container.page =${container.page}");
    HttpRequestUtil().get("topnews/index", param: {
      "page": container.page,
      "num":20
    }).then((value) {
      List newslist = value["newslist"];
      List<NewsModel> list = newslist.map((e) => NewsModel.fromJsonMap(e)).toList();
      container.acceptData(list,isRefresh: isRefresh);
      setState(() {});
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
